/**
 * Created by liuqingxia on 2015/12/8.
 */

/**
 * 获取工程名称
 */
function getRoot() {
	return contextPath;
}

/**
 * 获取Htpp根目录
 * 
 * @returns {string}
 */
function getProjectName() {
	var curWwwPath = window.document.location.href;
	var pathName = window.document.location.pathname;
	var pos = curWwwPath.indexOf(pathName);
	var projectName = pathName
			.substring(0, pathName.substr(1).indexOf('/') + 1);
	return projectName;
}

/**
 * 根据表单id获取表单参数
 * 
 * @param id
 * @returns {{}}
 */
function getFormParams(id) {
	var params = {};
	if (isNull(id)) {
		return params;
	}
	id = $.trim(id);
	var formId = "#" + id;
	$.each($(formId).find(".form-control"), function() {
		var name = $(this).attr("name");
		if (isNull(name)) {
			return true;
		}
		var value = $(this).val();
		if (typeof (value) == "undefined") {
			value = "";
		}
		value = $.trim(value);
		params[name] = value;
	});
	return params;
}

/**
 * 根据表单id获取表单input参数
 * 
 * @param id
 * @returns {{}}
 */
function getFormInputParams(id) {
	var params = {};
	if (isNull(id)) {
		return params;
	}
	id = $.trim(id);
	var formId = "#" + id;
	$.each($(formId).find(".form-control"), function() {
		var name = $(this).attr("name");
		if (isNull(name)) {
			return true;
		}
		var value = $(this).val();
		if (typeof (value) == "undefined") {
			value = "";
		}
		value = $.trim(value);
		params[name] = value;
	});
	return params;
}

/**
 * 发送异步post请求
 */
jQuery.extend({
	postHttp : function(params, url, func) {
		$.ajax({
			url : url,
			type : 'POST',
			dataType : 'json',
			data : params,
			success : func
		});
	}
});

/**
 * 发送同步post请求
 */
jQuery.extend({
	postHttpSync : function(params, url, func) {
		$.ajax({
			url : url,
			type : 'POST',
			async : false,
			dataType : 'json',
			data : params,
			success : func
		});
	}
});

/**
 * 提取表单数据，并通过http请求访问后台
 * 
 * @param formId
 * @param commitBtnId
 * @param url
 */
function postFormHttp(formId, commitBtnId, url) {
	var btnId = "#" + commitBtnId;
	$(document).on(
			"click",
			btnId,
			function() {
				var params = getFormParams(formId);
				params['moduleName'] = $("#moduleSelectId option:selected")
						.attr("alt");
				try {
					$.postHttp(params, url, function(json) {
						if (json && json.success) {
							swal("成功", json['message'], "success");
						} else {
							if (json) {
								swal("失败", json['message'], 'error');
							}
						}
					})
				} catch (e) {
					swal("失败", "通信异常，请检查网络配置后重试", 'error');
				}
				return;
			});
}

/**
 * 根据传入的表单id，获取各表单项值 如果发现有一表单项值为空，则停止获取， 先调用isSkipProp（）判断此项是否可以不填，
 * 若为必填，则把为空的表单项名称返回 若为选填，则略过此表单项
 * 
 * @param id
 * @param nullPropHandler
 * @returns {{}}
 */
function getFormValues(id, isSkipProp) {
	var params = {};
	var formId = "#" + $.trim(id);
	$.each($(formId).find(".form-control"), function() {
		var name = $(this).attr("name");
		if (!isNull(name)) {
			var value = $(this).val();
			if (isNull(value)) {
				if (isSkipProp(name)) {
					return true;// 等同continue
				}
				params['nullProp'] = name;
				params['hasNullProp'] = true;
				return false;// 结束$.each（）循环
			}
			params[name] = value;
		}
	});
	return params;
}

/**
 * 获取表单项值，如果某一项为空，则赋值为""
 * 
 * @param formId
 * @returns {{}}
 */
function getFormValuesNotSkip(formId) {
	var params = {};
	formId = "#" + $.trim(formId);
	$.each($(formId).find(".form-control"), function() {
		var name = $(this).attr("name");
		if (!isNull(name)) {
			var value = $(this).val();
			if (isNull(value)) {
				params[name] = "";
			} else {
				params[name] = value;
			}
			return true;
		}
	});
	return params;
}
/**
 * 获取表单项值，如果某一项为空，则跳过该项，不予赋值.
 * 
 * @param formId
 * @returns {{}}
 */
function getFormValuesSkip(formId) {
	var params = {};
	formId = "#" + $.trim(formId);
	$.each($(formId).find(".form-control"), function() {
		var name = $(this).attr("name");
		if (!isNull(name)) {
			var value = $(this).val();
			if (!isNull(value)) {
				params[name] = value;
			}
			return true;
		}
	});
	return params;
}

/**
 * 根据路径后缀获取url
 * 
 * @param suffix
 */
function getUrlBySuffix(suffix) {
	return getRoot() + suffix;
}

/**
 * 显示后台传回的json信息
 * 
 * @param json
 */
function showJsonMsg(json) {
	if (json && json.success) {
		swal("成功,1秒后自动刷新", json['message'], "success");
		window.setTimeout(function() {
			window.location.reload();
		}, 1000);
	} else {
		if (json) {
			swal("失败", json['message'], 'error');
		}
	}
}

/**
 * 根据id，指定url获取对象
 * 
 * @param url
 * @param id
 */
function getObjectById(url, id) {
	var params = {};
	params['id'] = id;
	var obj;
	$.postHttpSync(params, url,
			function(json) {
				if (json && json.success) {
					var list = json['list'];
					obj = list[0];
				}
				if (json.message == '您没有权限') {
					swal("权限-ERROR", "你不在此任务项目组中或者任务项目组权限变更,请删除此任务或者变更所在项目组！",
							"error");
				}
			});
	return obj;
}

/**
 * 根据给定对象， 把对象的各属性值填充到编辑表格中
 * 
 * @param job
 */
function fillEditForm(obj) {
	$.each($('#editForm').parent().find(".form-control"), function() {
		var name = $(this).attr("name");
		if (isNull(name)) {
			return true;
		}
		name = $.trim(name);
		var value = obj[name];
		$(this).val(value);
	});
}

/**
 * click password show
 */
function clickPasswordShow(clickId, butId) {
	$("#" + clickId).mousedown(function() {
		$("#" + butId).attr("type", "text");
	});
	$("#" + clickId).mouseup(function() {
		$("#" + butId).attr("type", "password");
	});
}

/**
 * ajax 请求角色列表
 * 
 * @param
 */
function ajaxRequestRoleList() {
	var url = getRoot() + "/admin/ajaxGetAllRoles";
	$.post(url, function(mav) {
		var roleListArray = mav;
		for (var i = 0; i < roleListArray.length; i++) {
			var str = "<option value='" + roleListArray[i].name + "' id='"
					+ roleListArray[i].id + "'>" + roleListArray[i].name
					+ "</option>";
			$("#userOptId").append(str);
		}
	});
}
function lookResult(index) {
	var resultStr = $("#currentResultValue_" + index).val();
	var objectJson = JSON.parse(resultStr);
	var table = showTableResult(objectJson);
	$("#esTable").empty();
	$("#esTable").append(table);
	$("#tableDataGenerator-modal").modal("show");
}

function showTableResult(result) {
	var table = "";

	var table_start = "<table cellspacing='1' width='auto;' border='1' class='imagetable' id='infoTable'>";
	var table_end = "</table>";

	table += table_start;

	var columnNames = getColumnNames(result);

	/**
	 * 获取thead
	 * 
	 * @param result
	 * @returns {string}
	 */
	function generateThead(result) {

		var thead_start = "<thead><tr id='fhead'>";
		var thead_end = "</tr></thead>";

		var thead = "";
		thead += thead_start;

		for ( var index in columnNames) {
			thead += "<th nowrap='nowrap' class='th' data-sort='text'>"
					+ "<div>" + columnNames[index] + "</div>" + "</th>";
		}

		thead += thead_end;
		return thead;

	}

	/**
	 * 生成tbody
	 * 
	 * @param result
	 * @returns {string}
	 */
	function generateTbody(result) {

		var tbody = "";
		var tbody_start = "<tbody>";
		var tbody_end = "</tbody>";

		tbody += tbody_start;
		var results = result.data;
		var columnKeyArray = getColumnKeys(result);
		for ( var index in results) {
			/*
			 * if (index == 0) { continue; }
			 */
			tbody += "<tr class='rowsss'>";
			for ( var p in columnKeyArray) {
				var value = columnKeyArray[p];
				var tdConment;
				if (results[index][value] == 'undefined'
						|| results[index][value] == ''
						|| results[index][value] == null) {
					tdConment = "null";
				} else {
					tdConment = results[index][value];
				}
				tbody += "<td nowrap='nowrap' class='tl'>" + tdConment
						+ "</td>";
			}
			tbody += "</tr>";
		}
		tbody += tbody_end;
		return tbody;
	}

	table += generateThead(result) + generateTbody(result) + table_end;
	return table;
}
/**
 * 获取列名
 * 
 * @param result
 * @returns {Array}
 */
function getColumnNames(result) {
	var row = result.displayColumns;
	var columns = [];
	for (var i = 1; i < result.displayColumns.length; i++) {
		columns.push(row[i].text);
	}
	return columns;
}
/**
 * 获取列的key值
 * 
 */
function getColumnKeys(result) {
	var row = result.displayColumns;
	var columnKeys = [];
	for (var i = 1; i < result.displayColumns.length; i++) {
		columnKeys.push(row[i].dataIndex);
	}
	return columnKeys;
}
function isEmpty(value) {
	return (value == "" || value == null || value == 'undefined');
}
/**
 * 跨域调取
 */
function readHttpJsonpInterface(ip, params) {
	var resultMap = {};
	$.ajax({
		type : "post",
		url : "http://" + ip + "/mcenter/websql/api/sqlupload",
		data : {
			pargs : "'" + params + "'"
		},
		dataType : 'jsonp',
		jsonp : 'callback',
		success : function(json) {
			$.extend(resultMap, json);
		}
	});
	console.log(resultMap);
}